//
//  UploadRequstTaskTool.m
//  NLProjectFrameworkDemo
//
//  Created by 陈志亮 on 2019/6/25.
//  Copyright © 2019 yj_zhang. All rights reserved.
//

#import "UploadRequstTaskTool.h"
#import "CommonHeader.h"


static NSString*KBASE_UPLOADIMG_URL=@"/bcp-war/sdk/uploadChatImg";

@implementation UploadRequstTaskTool

////上传图片任务
+(NSURLSessionDataTask *)uploadWithPictures:(UIImage *)image andMethod:(NSString *)method params:(NSDictionary *)params andDomainName:(NSString *)domainName onProgressBlock:(void(^)(NSProgress *uploadProgress))progressBlock onSuccessBlock:(NetworkSuccessBlock)successBlock onFailBlock:(NetworkFailureBlock)failBlock{
    NSMutableDictionary *mutParams = [[NSMutableDictionary alloc] init];
    [mutParams addEntriesFromDictionary:params];
   // [self getMustParams:mutParams withMethod:method];//添加后台需要固定参数
    AFHTTPSessionManager *manager = [MantisRequestManager shareManager].httpManager;
    
    
    // 设置请求头
    [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    NSString*baseUrlStr =[[MantisSDKTool keyManitsSDKTool].KWEBBASEURL stringByAppendingString: KBASE_UPLOADIMG_URL];
    NSURLSessionDataTask*uploadTask = [manager POST:[NSString stringWithFormat:@"%@",baseUrlStr] parameters:mutParams headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        CGImageRef imgRef = image.CGImage;
               CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imgRef);//获取照片是否有alpha通道
               NSInteger channels = 3;//默认RGB
               if(alphaInfo==kCGImageAlphaNone){//RBG
                   channels = 3;
               }else if(alphaInfo==kCGImageAlphaOnly){
                   //三个通道都是一样来表示alpha
                   channels = 3;
               }else{//四通道
                   channels = 4;
               }
               channels = 3; //暂时写死吧
               CGFloat width = image.size.width;
               CGFloat height = image.size.height;
               NSData *oriData = channels==3?UIImageJPEGRepresentation(image,1.0):UIImagePNGRepresentation(image);
               if(!oriData) return ;
               NSUInteger sizeOrigin  = oriData.length;
               NSUInteger sizeOriginKB = sizeOrigin / 1024.0;
               NSData *imageData = nil;
               CGFloat calLength = width * height * channels  ;//全彩
               CGFloat compressionRation = oriData.length/calLength;
               CGFloat minRate = 0.2;//最小压缩比
               if(width/height>(22.0/9)||width/height<(9/22.0)){//长图
                   if(compressionRation<=minRate){
                       imageData = oriData;
                   }else{
                       imageData = [image resetSizeOfImageData:image maxSize:sizeOriginKB*minRate];
                   }
               }else{
                   if(compressionRation>minRate){
                       CGFloat maxSize = sizeOriginKB<=700?200:sizeOriginKB*minRate;
                       imageData = [image resetSizeOfImageData:image maxSize:maxSize];
                   }else{
                       imageData = [image resetSizeOfImageData:image maxSize:200];
                   }
               }
               
               NSLog(@"压缩到%ldKB",(NSInteger)(imageData.length/1024.0));
               NSLog(@"%ldM",(NSInteger)((oriData.length/1024.0)/1024));
               
               NSString *name = params[@"name"];
               if ([[name lowercaseString] containsString:@".heic"]) {
                   name = [name stringByReplacingOccurrencesOfString:@".heic" withString:@".png"];
                   name = [name stringByReplacingOccurrencesOfString:@".HEIC" withString:@".png"];
               }
               
               if (name.length == 0) {
                   name = @"1.png";
               }
               
               if ([params[@"compress"] integerValue] == 1) { // 不压缩
                   [formData appendPartWithFileData:oriData name:@"files" fileName:name mimeType:@"image/jpg/png/heic"];
               } else {
                   [formData appendPartWithFileData:imageData name:@"files" fileName:name mimeType:@"image/jpg/png/heic"];
               }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
          !progressBlock?:progressBlock(uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        successBlock(responseObject,nil);
            [self printAPIWithParams:mutParams task:task];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error,nil);
              [self printAPIWithParams:mutParams task:task];
    }];

    return uploadTask;
}
//签名
+ (NSString *)getSignatureParams:(NSMutableDictionary *)MuDic withSecret:(NSString*)secretStr
{
    NSArray *keys = [MuDic allKeys];
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return [obj1 compare:obj2 options: NSNumericSearch];
    }];
    
    NSString *MyCommpareStr = @"" ;//拼接的string
    for (NSString *categoryId in sortedArray)
    {
        MyCommpareStr = [MyCommpareStr stringByAppendingFormat:@"%@%@",categoryId,[MuDic objectForKey:categoryId]];
    }
    MyCommpareStr = [secretStr stringByAppendingString:MyCommpareStr];
    return [MyCommpareStr jk_md5String];
}

//打印接口
+ (void)printAPIWithParams:(NSMutableDictionary *)params task:(NSURLSessionTask *)task{
    //请求的url拼接
    
    NSString  *myUrlCompareStr = [NSString stringWithFormat:@"%@?",task.currentRequest.URL];
    int i =0;
    for (NSString *keyStr in params.allKeys)
    {
        if (i==0)
        {
            myUrlCompareStr  = [NSString stringWithFormat:@"%@%@=%@",myUrlCompareStr,keyStr,params[keyStr]];
        }
        else
        {
            myUrlCompareStr  = [NSString stringWithFormat:@"%@&%@=%@",myUrlCompareStr,keyStr,params[keyStr]];
        }
        
        i++;
    }
    NSLog(@"后台要的url是-----%@",myUrlCompareStr);
}

//后台需要固定参数
+(void)getMustParams:(NSMutableDictionary *)mutParams withMethod:(NSString *)method{
   
    mutParams[@"app_version"] = [NSObject jk_version];
    mutParams[@"app_type"] = @"iOS";
    mutParams[@"method"] = method;
//    mutParams[@"session"] = kUserToken;
}








@end
